package com.link.linkupjavaweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.dto.UserLoginDTO;
import com.link.linkupjavaweb.dto.UserManageDTO;
import com.link.linkupjavaweb.dto.UserRegisterDTO;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.mapper.UserMapper;
import com.link.linkupjavaweb.service.UserService;
import com.link.linkupjavaweb.utils.AccountGenerator;
import com.link.linkupjavaweb.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户Service实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String register(UserRegisterDTO registerDTO, MultipartFile avatarFile) throws Exception {
        // 1. 验证手机号是否已注册
        User existUser = userMapper.selectByPhone(registerDTO.getPhone());
        if (existUser != null) {
            throw new Exception("该手机号已被注册");
        }
        
        // 2. 验证密码
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            throw new Exception("两次输入的密码不一致");
        }
        
        // 3. 生成唯一账号
        String account = AccountGenerator.generateAccount();
        
        // 4. 处理头像上传
        String avatarPath = Constants.DEFAULT_AVATAR;
        if (avatarFile != null && !avatarFile.isEmpty()) {
            try {
                avatarPath = FileUtils.saveAvatar(avatarFile, Constants.AVATAR_UPLOAD_PATH);
            } catch (Exception e) {
                // 头像上传失败不影响注册，使用默认头像
                System.err.println("头像上传失败: " + e.getMessage());
            }
        }
        
        // 5. 创建用户对象
        User user = new User();
        user.setAccount(account);
        user.setPhone(registerDTO.getPhone());
        user.setPassword(registerDTO.getPassword());
        user.setNickname(registerDTO.getNickname());
        user.setAvatar(avatarPath);
        user.setTotalScore(0);
        user.setWinCount(0);
        user.setLoseCount(0);
        user.setGameCount(0);
        user.setMaxCombo(0);
        user.setOnlineStatus(Constants.ONLINE_STATUS_OFFLINE);
        user.setStatus(Constants.USER_STATUS_NORMAL);
        user.setCreateTime(LocalDateTime.now());
        
        // 6. 保存到数据库
        userMapper.insert(user);
        
        return account;
    }
    
    @Override
    public User login(UserLoginDTO loginDTO) {
        // 1. 根据账号或手机号查询用户
        User user = userMapper.selectByAccountOrPhone(loginDTO.getAccount());
        
        // 2. 验证用户是否存在
        if (user == null) {
            throw new RuntimeException("账号或手机号不存在");
        }
        
        // 3. 验证账号是否被禁用
        if (user.getStatus().equals(Constants.USER_STATUS_DISABLED)) {
            throw new RuntimeException("该账号已被禁用，请联系管理员");
        }
        
        // 4. 验证密码
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 5. 更新最后登录时间和在线状态
        user.setLastLoginTime(LocalDateTime.now());
        user.setOnlineStatus(Constants.ONLINE_STATUS_ONLINE);
        userMapper.updateById(user);
        
        return user;
    }
    
    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public void updateOnlineStatus(Long userId, Integer onlineStatus) {
        User user = new User();
        user.setId(userId);
        user.setOnlineStatus(onlineStatus);
        userMapper.updateById(user);
    }
    
    @Override
    public Map<String, Object> getUserList(Integer page, Integer size, String keyword) {
        // 设置默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        
        // 创建分页对象
        Page<User> pageObj = new Page<>(page, size);
        
        // 构建查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("account", keyword)
                    .or().like("nickname", keyword)
                    .or().like("phone", keyword));
        }
        wrapper.orderByDesc("create_time");
        
        // 执行分页查询
        IPage<User> pageResult = userMapper.selectPage(pageObj, wrapper);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        result.put("pages", pageResult.getPages());
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User addUser(UserManageDTO userDTO) throws Exception {
        // 1. 验证手机号是否已存在
        User existUser = userMapper.selectByPhone(userDTO.getPhone());
        if (existUser != null) {
            throw new Exception("该手机号已被注册");
        }
        
        // 2. 生成唯一账号
        String account = AccountGenerator.generateAccount();
        
        // 3. 创建用户对象
        User user = new User();
        user.setAccount(account);
        user.setPhone(userDTO.getPhone());
        user.setPassword(userDTO.getPassword());
        user.setNickname(userDTO.getNickname());
        user.setAvatar(userDTO.getAvatar() != null ? userDTO.getAvatar() : Constants.DEFAULT_AVATAR);
        user.setTotalScore(0);
        user.setWinCount(0);
        user.setLoseCount(0);
        user.setGameCount(0);
        user.setMaxCombo(0);
        user.setOnlineStatus(Constants.ONLINE_STATUS_OFFLINE);
        user.setStatus(userDTO.getStatus() != null ? userDTO.getStatus() : Constants.USER_STATUS_NORMAL);
        user.setCreateTime(LocalDateTime.now());
        
        // 4. 保存到数据库
        userMapper.insert(user);
        
        return user;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(UserManageDTO userDTO) throws Exception {
        // 1. 验证用户是否存在
        User user = userMapper.selectById(userDTO.getId());
        if (user == null) {
            throw new Exception("用户不存在");
        }
        
        // 2. 如果修改了手机号，验证新手机号是否已被使用
        if (!user.getPhone().equals(userDTO.getPhone())) {
            User existUser = userMapper.selectByPhone(userDTO.getPhone());
            if (existUser != null && !existUser.getId().equals(userDTO.getId())) {
                throw new Exception("该手机号已被使用");
            }
        }
        
        // 3. 更新用户信息
        user.setPhone(userDTO.getPhone());
        user.setPassword(userDTO.getPassword());
        user.setNickname(userDTO.getNickname());
        if (userDTO.getAvatar() != null) {
            user.setAvatar(userDTO.getAvatar());
        }
        if (userDTO.getStatus() != null) {
            user.setStatus(userDTO.getStatus());
        }
        
        // 4. 保存更新
        return userMapper.updateById(user) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long userId) {
        return userMapper.deleteById(userId) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserStatus(Long userId, Integer status) {
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        return userMapper.updateById(user) > 0;
    }
}

